package doc.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author eollse
 */
public class MD5Utils {
	private static final String hexDigIts[] = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
	

	 public static String MD5Encode(String origin, String charsetName){
	        String resultString = origin;
	        try{
	            MessageDigest md = MessageDigest.getInstance("MD5");
	            if(null == charsetName || "".equals(charsetName)){
	                resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
	            }else{
	                resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetName)));
	            }
	        }catch (Exception e){
	        }
	        return resultString;
	}
	 public static String byteArrayToHexString(byte b[]){
		StringBuffer resultSb = new StringBuffer();
		for(int i = 0; i < b.length; i++){
			resultSb.append(byteToHexString(b[i]));
		}
		return resultSb.toString();
	}

	public static String byteToHexString(byte b){
		int n = b;
		if(n < 0){
			n += 256;
		}
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigIts[d1] + hexDigIts[d2];
	}

	/**
	 * 将普通字符串用md5加密，并转化为16进制字符串
	 * 32位小写
	 * @param str
	 * @return
	 */
	public static String stringInMd5(String str) {
		// 消息签名（摘要）
		MessageDigest md5;
		try {
			// 参数代表的是算法名称
			md5 = MessageDigest.getInstance("md5");
			byte[] result = md5.digest(str.getBytes());
			StringBuilder sb = new StringBuilder(32);
			// 将结果转为16进制字符  0~9 A~F
			for (int i = 0; i < result.length; i++) {
				// 一个字节对应两个字符
				byte x = result[i];
				// 取得高位
				int h = 0x0f & (x >>> 4);
				// 取得低位
				int l = 0x0f & x;
				sb.append(hexDigIts[h]).append(hexDigIts[l]);
			}
			return sb.toString();
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 将传进来的无序参数,转换为有序的字符串输出
	 *
	 * @param map
	 * @return
	 */
	public static String getASCIISortMap(Map<String, Object> map) {
		String result;
		try {
			List<Map.Entry<String, Object>> infoIds = new ArrayList<>(map.entrySet());
			// 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
			List<Map.Entry<String, Object>> collection = infoIds.stream().sorted(Comparator.comparing(Map.Entry::getKey)).collect(Collectors.toList());
			// 构造签名键值对的格式
			StringBuilder sb = new StringBuilder();
			for (Map.Entry<String, Object> item : collection) {
				if (item.getKey() == null) {
					item.getKey();
				}
				String key = item.getKey();
				String val = item.getValue().toString();
				if (!val.equals("")) {
					sb.append(key).append(val);
				}

			}
			result = sb.toString();
		} catch (Exception e) {
			return null;
		}
		return result;
	}
}
